import { PlusOutlined } from '@ant-design/icons';
import {
  type ActionType,
  ModalForm,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
  ProFormSwitch,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, message, TreeSelect } from 'antd';
import type { FC } from 'react';
import { addCategory, editCategory } from '@/services/ant-design-pro/api';

interface CreateFormProps {
  reload?: ActionType['reload'];
  data?: Array<any>;
  values?: any;
}

const CreateForm: FC<CreateFormProps> = (props) => {
  const { reload, data, values } = props;
  console.log("🚀 ~ CreateForm ~ reload:", reload)
  const [messageApi, contextHolder] = message.useMessage();
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const { run, loading } = useRequest(values ? editCategory : addCategory, {
    manual: true,
    onSuccess: () => {
      messageApi.success(values ? '修改成功' : '添加成功');
      reload?.();
    },
    onError: () => {
      messageApi.error(values ? '修改失败' : '添加失败');
    },
  });

  return (
    <>
      {contextHolder}
      <ModalForm
        title={values ? "编辑分类" : "新建分类"}
        onOpenChange={(open) => {
          if (open) {
            console.log("reload", reload)
            // setSkuData([])
          }
        }}
        trigger={
          values ? (
            <a>编辑</a>
          ) : (
            <Button type="primary" icon={<PlusOutlined />}>
              新建
            </Button>
          )
        }
        width="400px"
        modalProps={{ okButtonProps: { loading }, destroyOnClose: true }}
        onFinish={async (value) => {
          console.log("value", value)
          value.parentId = value.parentId ? value.parentId : 0
          value.status = value.status ? 1 : 2
          if (values.id) {
            value.id = values.id
          }
          await run(value as API.RuleListItem);
          return true;
        }}
      >
        <ProFormTreeSelect
          initialValue={values?.parentId || ""}
          label="选择上级分类"
          fieldProps={{
            fieldNames: {
              label: 'name',
              value: 'id',
            },
            treeData: data,
          }}
          width="md"
          name="parentId"
          placeholder="请选择上级分类"
        />
        <ProFormText
          initialValue={values?.name}
          rules={[
            {
              required: true,
              message: '分类名称必填',
            },
          ]}
          width="md"
          name="name"
          label="分类名称"
          placeholder="请输入分类名称"
        />
        <ProFormSwitch 
          initialValue={values?.status === 1}
          width="md"
          name="status"
          label="状态"/>
      </ModalForm>
    </>
  );
};

export default CreateForm;
